import { Body, Controller, Delete, Get, Param, ParseIntPipe, Post, Put, Req } from '@nestjs/common';
import { MenuService } from './menu.service';
import { ReqAttrs } from 'apps/admin/src/constant';
import { ResponseUtilService } from '@app/response-util';
import { DtoPipe } from 'apps/admin/src/pipe/dto/dto.pipe';
import CreateDto from './dto/create.dto';
import UpdateDto from './dto/update.dto';

@Controller('menu')
export class MenuController {
    constructor(
        private readonly service:MenuService
    ){}


    @Post('add')
    async add(@Body(new DtoPipe()) dto:CreateDto) {
        try {
            const r = await this.service.add(dto)
            return r ? ResponseUtilService.successRes() : ResponseUtilService.failRes()
        } catch (error) {
            return ResponseUtilService.failRes(error.message)
        }
    }

    @Put('update')
    async update(@Body(new DtoPipe()) dto:UpdateDto) {
        try {
            const r = await this.service.update(dto)
            return r ? ResponseUtilService.successRes() : ResponseUtilService.failRes()
        } catch (error) {
            return ResponseUtilService.failRes(error.message)
        }
    }

    @Delete('delete/:id')
    async del(@Param('id', ParseIntPipe) id:number) {
        if(id < 1) return null
        try {
            const r = await this.service.del(id)
            return r ? ResponseUtilService.successRes() : ResponseUtilService.failRes()
        } catch (error) {
            return ResponseUtilService.failRes(error.message)
        } 
    }

    @Get('permission')
    async permission(@Req() req) {
        const memberId = req[ReqAttrs.MEMBER_ID];
        const menus = await this.service.availableMenu(memberId)
        
        return ResponseUtilService.successRes(menus)
    }

    @Get('list')
    async list(@Req() req) {
        const memberId = req[ReqAttrs.MEMBER_ID];
        const menus = await this.service.list(memberId)
        return ResponseUtilService.successRes(menus)
    }
}
